package com.decoration.basic.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;
import java.util.Arrays;

public class WechatGetUserInfoUtil {

    //日志记录器
    private static final Logger log= LoggerFactory.getLogger(WechatGetUserInfoUtil.class);
    /**
     * 微信小程序登录
     */
    // 小程序唯一标识 (在微信小程序管理后台获取)
    static final String WXSPAPPID = "wx8f6dc9822b9a3127";
    // 小程序的 app secret (在微信小程序管理后台获取)
    static final String WXSPSECRET = "117369459e371bdcc56bc2d7a6aff63d";
    // 授权（必填）
    static final String  GRANT_TYPE_LOGIN = "authorization_code";
    //请求地址
    static final String  WECHAT_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 解密用户敏感数据获取用户信息
     *
     * @param sessionKey    数据进行加密签名的密钥
     * @param encryptedData 包括敏感数据在内的完整用户信息的加密数据
     * @param iv            加密算法的初始向量
     * @return
     * */
    public static JSONObject getUserInfo(String encryptedData, String sessionKey, String iv) {
        // 被加密的数据
        byte[] dataByte = Base64Utils.decode(encryptedData.getBytes());
        // 加密秘钥
        byte[] keyByte = Base64Utils.decode(sessionKey.getBytes());
        // 偏移量
        byte[] ivByte = Base64Utils.decode(iv.getBytes());
        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化

            byte[] resultByte = cipher.doFinal(dataByte);

            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                return JSON.parseObject(result);
            }
        } catch (NoSuchAlgorithmException e) {
            log.error(e.getMessage(), e);
        } catch (NoSuchPaddingException e) {
            log.error(e.getMessage(), e);
        } catch (InvalidParameterSpecException e) {
            log.error(e.getMessage(), e);
        } catch (IllegalBlockSizeException e) {
            log.error(e.getMessage(), e);
        } catch (BadPaddingException e) {
            log.error(e.getMessage(), e);
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage(), e);
        } catch (InvalidKeyException e) {
            log.error(e.getMessage(), e);
        } catch (InvalidAlgorithmParameterException e) {
            log.error(e.getMessage(), e);
        } catch (NoSuchProviderException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 获取微信小程序的用户openid和session_key/unionid
     * 返回格式：{"session_key":"ZXxmVGt78993dkNCPmQOA==","openid":"o5TI441P58849p4E-fBrH_HgVvGo","unionid":"oD08m1s24646ZIDJ_AQ9ADUf5QQ"}
     * @param code
     * @return
     * @throws Exception
     * @return JSONObject
     * @author tyg
     * @date   2019年4月25日下午2:24:22
     */
    public static JSONObject getWechatSmallProgram(String code){

        if (code.equals("") ||code ==null){
            return null;
        }

        //1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid
        // 请求参数
        StringBuffer params = new StringBuffer(WECHAT_LOGIN_URL).append("?appid=").append(WXSPAPPID);
        params.append("&secret=").append(WXSPSECRET);
        params.append("&js_code=").append(code);
        params.append("&grant_type=").append(GRANT_TYPE_LOGIN);

        //String data = HttpTookit.doGet(url, params.toString());
        String data = HttpTookit.doGet(params.toString(),"", null);
        if (data == null){
            return null;
        }
        log.info("\n微信小程序用户信息："+data);
        return JSONObject.parseObject(data);
    }
}
